package com.wing.cabinet.controller.websocket.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wing.api.ApplicationContextUtil;
import com.wing.cabinet.controller.websocket.CabinetOpenServer;
import com.wing.cabinet.controller.websocket.service.BaseConnectService;
import com.wing.cabinet.model.entity.CommandLog;
import com.wing.cabinet.service.CommandLogService;
import com.wing.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 远程开柜的反馈
 * {"client":"cab","cabCode":"SKU-ZG01-20221017-1","createTime":"2024-01-23 11:32:50.341","enterpriseCode":"Z0005","type":"remoteOpenCab","remark":"备注","spaceCode":"货道","command":"指令"}
 */
@Service
@Slf4j
public class RemoteOpenCabServiceImpl implements BaseConnectService {

    @Override
    public void logicMessage(String message) throws IOException {
        log.debug("收到消息:"+message);
        JSONObject jsonObject = JSONObject.parseObject(message);
        String type = jsonObject.getString("type"); //消息类型 remoteOpenCab
        String enterpriseCode = jsonObject.getString("enterpriseCode");  // 企业编号
        String cabCode = jsonObject.getString("cabCode"); //柜子编号
        String client = jsonObject.getString("client"); //客户端
        String createTime = jsonObject.getString("createTime"); //发送时间
        String remark = jsonObject.getString("remark"); //备注
        String spaceCode = jsonObject.getString("spaceCode"); //货道编号
        String command = jsonObject.getString("command"); //指令内容

        CommandLogService commandLogService = (CommandLogService) ApplicationContextUtil.getBean("commandLogServiceImpl");
        CommandLog commandLog = new CommandLog();
        commandLog.setCabCode(cabCode);
        commandLog.setEnterpriseCode(enterpriseCode);
        commandLog.setCommand(message);
        commandLog.setCommand(command);
        commandLog.setSpaceCode(spaceCode);
        commandLog.setRemark(remark);
        commandLog.setCreateTime(createTime);
        commandLog.setType(CommandLog.Type.remoteOpenCab);
        commandLogService.save(commandLog);

        JSONObject result = new JSONObject();
        result.put("type", type);
        result.put("enterpriseCode", enterpriseCode);
        result.put("cabCode", cabCode);
        result.put("client", client);

        try {
            CabinetOpenServer.sendMessage(enterpriseCode, cabCode, result.toJSONString());
        }catch (Exception e){
            throw new BusinessException("心跳包处理失败:"+e.getMessage());
        }

    }


}
